package com.qf.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.validator.PublicClassValidator;
import sun.security.action.PutAllAction;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*
杨威
2021/9/19
17:53
*/
public class DruidUtil {
    private static DruidDataSource ds;
    private static ThreadLocal<Connection> threadLocal=new ThreadLocal();
    static {
        Properties properties=new Properties();
        InputStream stream = DruidUtil.class.getResourceAsStream("/db.properties");
        try {
            properties.load(stream);
            ds= (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection connection = threadLocal.get();
        if(connection==null){
            try {
                connection=ds.getConnection();
                threadLocal.set(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }
    public static void begin(){
        try {
            getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void commit(){
        try {
            getConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void rollBack(){
        try {
            getConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close(){
        try {
            getConnection().close();
            threadLocal.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
